'use client';

import React, { useState, useEffect } from 'react';
import { useAuth } from '../contexts/AuthContext';
import LoginForm from './LoginForm';
import TodoList from './TodoList';
import NotificationDropdown from './NotificationDropdown';
import { notificationApi } from '../services/notificationApi';

// 动态加载AdminDashboard
let AdminDashboardComponent: React.ComponentType<any> | null = null;
try {
  AdminDashboardComponent = require('./AdminDashboard').default;
} catch (e) {
  console.error('无法加载管理员面板:', e);
}

const AuthenticatedApp: React.FC = () => {
  const { isAuthenticated, user, logout, loading, login, isAdmin } = useAuth();
  const [currentView, setCurrentView] = useState<'todos' | 'admin'>('todos');
  const [showNotifications, setShowNotifications] = useState(false);
  const [unreadCount, setUnreadCount] = useState(0);

  // 获取未读通知数量
  const fetchUnreadCount = async () => {
    if (!isAuthenticated || !user) return;
    
    try {
      const response = await notificationApi.getNotifications(1, true); // 只获取未读通知数量
      setUnreadCount(response.unread_count);
    } catch (error) {
      console.error('获取通知数量失败:', error);
    }
  };

  // 定时检查未读通知
  useEffect(() => {
    if (isAuthenticated && user) {
      fetchUnreadCount();
      // 每30秒检查一次
      const interval = setInterval(fetchUnreadCount, 30000);
      return () => clearInterval(interval);
    }
  }, [isAuthenticated, user]);

  // 显示加载状态
  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">加载中...</p>
        </div>
      </div>
    );
  }

  // 如果未认证，显示登录界面
  if (!isAuthenticated) {
    return <LoginForm onLogin={login} loading={loading} />;
  }

  // 如果已认证，显示简单的用户信息
  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50">
      {/* 用户信息栏 */}
      <div className="bg-white/80 backdrop-blur-sm border-b border-white/20 shadow-sm">
        <div className="max-w-6xl mx-auto px-4 py-3 flex justify-between items-center">
          <div className="flex items-center space-x-3">
            <div className="w-8 h-8 bg-gradient-to-r from-blue-600 to-purple-600 rounded-full flex items-center justify-center">
              <span className="text-white font-medium text-sm">
                {user?.username?.charAt(0).toUpperCase()}
              </span>
            </div>
            <div>
              <p className="font-medium text-gray-900">欢迎回来，{user?.username}!</p>
              <p className="text-sm text-gray-500">
                {isAdmin ? '管理员面板' : '管理您的待办事项'}
                {isAdmin && (
                  <span className="ml-2 px-2 py-1 bg-red-100 text-red-800 text-xs rounded-full">管理员</span>
                )}
              </p>
            </div>
          </div>
          
          <div className="flex items-center space-x-3">
            {/* 导航按钮 - 仅管理员可见 */}
            {isAdmin && (
              <div className="flex space-x-2">
                <button
                  onClick={() => setCurrentView('todos')}
                  className={`px-3 py-1 text-sm rounded-lg transition-colors ${
                    currentView === 'todos'
                      ? 'bg-blue-600 text-white'
                      : 'bg-gray-100 hover:bg-gray-200 text-gray-700'
                  }`}
                >
                  我的任务
                </button>
                <button
                  onClick={() => setCurrentView('admin')}
                  className={`px-3 py-1 text-sm rounded-lg transition-colors ${
                    currentView === 'admin'
                      ? 'bg-blue-600 text-white'
                      : 'bg-gray-100 hover:bg-gray-200 text-gray-700'
                  }`}
                >
                  管理面板
                </button>
              </div>
            )}
            
            {/* 通知按钮 */}
            <div className="relative">
              <button
                onClick={() => setShowNotifications(!showNotifications)}
                className="relative p-2 text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded-lg transition-colors"
              >
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 17h5l-3.5-3.5a6 6 0 1 0-7 0L7 17h5m0 0v1a3 3 0 1 0 6 0v-1m-6 0V9" />
                </svg>
                {unreadCount > 0 && (
                  <span className="absolute -top-1 -right-1 bg-red-500 text-white text-xs rounded-full w-5 h-5 flex items-center justify-center">
                    {unreadCount > 99 ? '99+' : unreadCount}
                  </span>
                )}
              </button>
              
              <NotificationDropdown 
                isOpen={showNotifications} 
                onClose={() => setShowNotifications(false)} 
              />
            </div>
            
            <button
              onClick={logout}
              className="px-4 py-2 text-sm bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg transition-colors"
            >
              退出登录
            </button>
          </div>
        </div>
      </div>
      
      {/* 主内容区域 */}
      <div className="pt-6">
        {isAdmin && currentView === 'admin' ? (
          <React.Suspense fallback={<div className="text-center py-8 text-gray-500">管理员面板正在加载中...</div>}>
            {AdminDashboardComponent ? <AdminDashboardComponent /> : 
              <div className="text-center py-8 text-gray-500">管理员面板加载失败</div>
            }
          </React.Suspense>
        ) : (
          <TodoList />
        )}
      </div>
    </div>
  );
};

export default AuthenticatedApp;